﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace Lion.WeiXin.Core.Message
{
    /// <summary>
    /// 微信处理类
    /// </summary>
   public class WeiXinManager
    {
       /// <summary>
       ///  接收微信 post 的消息XML字符串
       /// </summary>
       /// <param name="message">XML消息字符串</param>
       /// <returns></returns>
       public string AcceptPost(string message)
       {
           string result = string.Empty;
           try
           {
               MsgModel requestMsg = new MsgModel(message);
               IMessageHandler ihander = CreateMessageHander();
               MsgModel responseMsg = ihander.Hander(requestMsg);
               Func<MsgModel, string> getXmlMsg = new Func<MsgModel, string>(GetTextFromMsg);
               result =getXmlMsg(responseMsg);
              // result = GetXMLFromMsg(responseMsg);
           }
           catch (Exception ex)
           {
               throw ex;
           }
           return result;         
       }

       private IMessageHandler CreateMessageHander()
       {
           return new TextHandler();
       }



       /// <summary>
       /// 接收微信 post 的消息流 ,默认UTF-8 编码
       /// </summary>
       /// <param name="postStream"></param>
       /// <returns></returns>
       public string AcceptPost(Stream inputStream)
       { 
           return AcceptPost(inputStream, Encoding.UTF8);
       }

       /// <summary>
       /// 接收微信post 的消息流，自定义编码
       /// </summary>
       /// <param name="inputStream">post消息流</param>
       /// <param name="encoding">消息编码</param>
       /// <returns></returns>
       public string AcceptPost(Stream inputStream,Encoding encoding)
       {
           byte[] data = new byte[inputStream.Length];
           inputStream.Read(data, 0, (int)inputStream.Length);
           string message = encoding.GetString(data);
           Tools.Log.LogHelper.Info("收到请求 message=\r\n{0}", message);
           return AcceptPost(message);
       }

       protected string GetTextFromMsg(MsgModel reMsg)
       {
           string responseXML =
           @"<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content></xml>";
           return string.Format(responseXML, reMsg.ToUserName, reMsg.FromUserName, reMsg.CreateTime, reMsg.MsgType, reMsg.ContentXML);
       }

       /// <summary>
       /// 微信开发者验证。使用Get请求获取查询字符串中前4个参数进行校验。验证成功返回echoStr，失败返回空字符串，需把返回值回推微信
       /// </summary>
       /// <param name="echoStr">随机字符串</param>
       /// <param name="signature">微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数</param>
       /// <param name="timestamp">时间戳</param>
       /// <param name="nonce">随机数</param>
       /// <param name="token">公众账号上的Token 签名</param>
       /// <returns></returns>
       public string FirstValid(string echoStr, string signature, string timestamp, string nonce, string token)
       {
           string result = string.Empty;
           if (CheckSignature(signature, timestamp, nonce,token))
           {
               result= echoStr;
           }
           return result;
       }

       private bool CheckSignature(string signature, string timestamp, string nonce, string token)
       {
           //string signature = Request["signature"];
           //string timestamp = Request["timestamp"];
           //string nonce = Request["nonce"];
           //string token = "thisismhsg100";
           string[] ArrTmp = { token, timestamp, nonce };
           Array.Sort(ArrTmp);     //字典排序
           string tmpStr = string.Join("", ArrTmp);
           tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");          
           tmpStr = tmpStr.ToLower();
           if (tmpStr == signature)
           {               
               return true;
           }
           else
           {
               return false;
           }
       }

       /// <summary>
       /// 发送Post 请求消息, 默认UTF-8 编码
       /// </summary>
       /// <param name="postUrl"></param>
       /// <param name="data"></param>
       /// <returns></returns>
       public string PostWebRequest(string postUrl, string data)
       {
           return PostWebRequest(postUrl, data, Encoding.UTF8);
       }

       /// <summary>
       /// 发送Post 请求消息
       /// </summary>
       /// <param name="postUrl">post 地址</param>
       /// <param name="data">post 内容</param>
       /// <param name="dataEncode">编码，默认是utf-8</param>
       /// <returns></returns>
       public string PostWebRequest(string postUrl, string data, Encoding dataEncode)
       {
           string ret = string.Empty;
           try
           {
               byte[] byteArray = dataEncode.GetBytes(data); //转化
               HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
               webReq.Method = "POST";
               webReq.ContentType = "application/x-www-form-urlencoded";

               webReq.ContentLength = byteArray.Length;
               Stream newStream = webReq.GetRequestStream();
               newStream.Write(byteArray, 0, byteArray.Length);//写入参数
               newStream.Close();
               HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
               StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
               ret = sr.ReadToEnd();
               sr.Close();
               response.Close();
               newStream.Close();
           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
           }
           return ret;
       }

       /// <summary>
       /// 发送get请求
       /// </summary>
       /// <param name="url"></param>
       /// <returns></returns>
       public string SendGetRequest(string url)
       {          
           // 对url发起一个Web请求
           HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
           if (webRequest != null)
           {
               // 返回回复结果
               using (WebResponse response = webRequest.GetResponse())
               {
                   using (Stream responseStream = response.GetResponseStream())
                   {
                       using (StreamReader reader = new StreamReader(responseStream))
                       {
                           return reader.ReadToEnd();
                       }
                   }
               }
           }
           return "";
       }
      
    }
}
